package com.club.football.service.impl;

import cn.hutool.core.text.StrPool;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.football.common.UserHolder;
import com.club.football.entity.Files;
import com.club.football.mapper.FilesMapper;
import com.club.football.service.FilesService;
import com.club.football.utils.FileUtils;
import com.club.football.utils.R;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Objects;

import static org.springframework.web.util.WebUtils.getRealPath;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@Service
public class FileServiceImpl extends ServiceImpl<FilesMapper, Files> implements FilesService {
    @Resource
    ServletContext servletContext;

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public R<String> filesUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return R.failed("无文件");
        }
        Files files = toFiles(file);
        Long userId = UserHolder.getUser().getUserId();
        files.setCreateBy(userId);
        files.setUpdateBy(userId);
        String applicationPath = getRealPath(servletContext, "");
        String uploadPath = applicationPath + "WEB-INF" + File.separator + "static";
        String fileName = IdWorker.getId() + StrPool.DOT + files.getType();
        String newFilePath = uploadPath + File.separator + fileName;
        files.setFileUrl(newFilePath);
        files.setFileName(fileName);
        File newFile = new File(newFilePath);
        file.transferTo(newFile);
        save(files);
        return R.ok(FileUtils.getImageUrl(fileName), "上传成功");
    }


    private Files toFiles(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int dotIndex = Objects.requireNonNull(originalFilename).lastIndexOf('.');
        String type = originalFilename.substring(dotIndex + 1);
        return Files.builder()
                .original(originalFilename)
                .fileSize(file.getSize())
                .type(type)
                .bucketName("local")
                .build();
    }
}
